#pragma once

#include "Socket.hpp"
#include <signal.h>
#include <unistd.h>
#include <functional>

using func_t = function<string(string&)>;

class TcpServer
{
public:
    TcpServer(uint16_t port,func_t callback)
        : _listensocket(), _port(port),_callback(callback)
    {
        ;
    }

    bool Init()
    {
        _listensocket.Bind(_port);
        _listensocket.Listen();

        lg(Info, "init server ...... done");

        return true;
    }

    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);

        while (true)
        {
            string ip;
            uint16_t port;
            int sockfd = _listensocket.Accept(&ip, &port);
            if (sockfd < 0)
            {
                continue;
            }
            lg(Info, "accept a new link, sockfd: %d, clientip: %s, clientport: %d", sockfd, ip.c_str(), port);

            // 多进程
            if (fork() == 0)
            {
                // child
                _listensocket.Close();
                string inbuffer_stream;

                while (true)
                {
                    char buffer[1024];
                    int n = read(sockfd, buffer, sizeof(buffer));
                    if (n > 0)
                    {
                        buffer[n] = '\0';
                        inbuffer_stream += buffer;

                        lg(Debug, "debug:\n%s", inbuffer_stream.c_str());

                        while(true)
                        {
                            string info = _callback(inbuffer_stream);
                            cout<<info<<endl;
                            if(info.empty())
                            {
                                break;
                            }

                            write(sockfd,info.c_str(),info.size());
                        }
                    }
                    else if(n == 0)
                    {
                        break;
                    }
                    else
                    {
                        break;
                    }
                }
                exit(0);
            }

            close(sockfd);
        }
    }

    ~TcpServer()
    {
        ;
    }

public:
    Socket _listensocket;
    uint16_t _port;
    func_t _callback;
};